package wailsutil

import (
	"embed"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/wailsapp/wails/v2/pkg/logger"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
)

type FileLoader struct {
	http.Handler
}

func NewFileLoader() *FileLoader {
	return &FileLoader{}
}

func (h *FileLoader) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	requestedFilename := strings.TrimPrefix(req.URL.Path, "/")
	//println("请求文件:", requestedFilename)
	fileData, err := os.ReadFile(requestedFilename)
	if err != nil {
		res.WriteHeader(http.StatusBadRequest)
		res.Write([]byte(fmt.Sprintf("读取文件 %s 异常", requestedFilename)))
		return
	}

	res.Write(fileData)
}

// jsBind 必须是指针
func WailsOptions(jsBind []interface{}, iconInfos map[string][]byte, assets embed.FS, uuid string) *options.App {
	dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	appConfigFile := dir + "/config/app.ini"

	onlyRun := ReadConfig(appConfigFile, "System", "OnlyRun") == "1" //仅允许一个应用实例运行

	// Root := ReadConfig(appConfigFile, "System", "Root")
	// Port := ReadConfig(appConfigFile, "System", "Port")
	// go staticServerRun(Root, Port)

	sTitle := ReadConfig(appConfigFile, "System", "Title")

	// isMaxWindow := ReadConfig(appConfigFile, "App", "isMaxWindow") == "1"
	// iWidth, _ := strconv.Atoi(ReadConfig(appConfigFile, "App", "iWidth"))
	// iHeight, _ := strconv.Atoi(ReadConfig(appConfigFile, "App", "iHeight"))

	sysType := runtime.GOOS

	// Create an instance of the app structure
	app := NewApp(appConfigFile, sysType)

	isWindows := sysType == "windows"
	if sysType == "windows" {
		//app.SetWindwIsShow(false)
		go SystemTray{}.Run(app, iconInfos)
	} else {
		app.SetWindwIsShow(true)
	}

	if jsBind == nil {
		jsBind = []interface{}{}
	}

	jsBind = append(jsBind, app)

	runOptions := &options.App{
		Title:  sTitle,
		Width:  app.GiWidth,
		Height: app.GiHeight,
		AssetServer: &assetserver.Options{
			Assets:  assets,
			Handler: NewFileLoader(), //静态资源访问器
		},
		BackgroundColour:   &options.RGBA{R: 27, G: 38, B: 54, A: 1}, //背景颜色
		OnStartup:          app.Startup,
		OnShutdown:         app.Shutdown,
		OnBeforeClose:      app.BeforeClose,
		Frameless:          false,               // 无边框模式 true;普通模式false
		CSSDragProperty:    "--wails-draggable", //指示用于标识哪些元素可用于拖动窗口的 CSS 属性。 默认值：--wails-draggable
		CSSDragValue:       "drag",              //指示 CSSDragProperty 样式应该具有什么值才能拖动窗口。 默认值：drag
		DisableResize:      false,               //禁用调整窗口尺寸
		Logger:             &CustomLogger{},
		LogLevel:           logger.DEBUG,
		LogLevelProduction: logger.INFO,
		StartHidden:        !app.WindwIsShow(), //启动时隐藏窗口
		HideWindowOnClose:  isWindows,          //关闭窗口时隐藏窗口,windows时有系统托盘
		Bind:               jsBind,             //js函数绑定
	}

	if app.GisMaxWindow { //最大化
		runOptions.WindowStartState = options.Maximised
	}

	if onlyRun && (uuid != "") {
		runOptions.SingleInstanceLock = &options.SingleInstanceLock{
			UniqueId: uuid,
			// OnSecondInstanceLaunch: func(secondInstanceData options.SecondInstanceData) {
			// 	activateWindow(sTitle)
			// },
		}
	}

	return runOptions
}

// 激活窗口
// func activateWindow(title string) {
// 	hWnd := win.FindWindow(nil, syscall.StringToUTF16Ptr(title))
// 	if hWnd != 0 {
// 		win.SetForegroundWindow(hWnd)
// 	} else {
// 		log.Printf("没有发现标题为 '%s' 的窗口", title)
// 	}
// }

// func staticServerRun(webRoot, port string) {
// 	//启动http服务
// 	http.Handle("/", http.FileServer(http.Dir("."+webRoot)))
// 	http.ListenAndServe(":"+port, nil)
// }
